﻿using AutoMapper;
using B.S.Sterilizationcenter.Domain.zyy;
using B.S.Sterilizationcenter.ErrorCode;
using B.S.Sterilizationcenter.Writer.API.Appliaction.Commends.WJL;
using MediatR;
using SqlSugar;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace B.S.Sterilizationcenter.Writer.API.Appliaction.CommandHandlers.WJL
{
    public class AddReturnApplicationCommandHanders : IRequestHandler<AddReturnApplicationCommands, ApiResult<int>>
    {
        private readonly ISqlSugarClient db;
        private readonly IMapper mapper;

        public AddReturnApplicationCommandHanders(ISqlSugarClient db, IMapper mapper)
        {
            this.db = db;
            this.mapper = mapper;
        }

        /// <summary>
        /// 保存回收信息及关联物品
        /// </summary>
        /// <param name="request">包含回收信息和物品列表的请求命令对象</param>
        /// <param name="cancellationToken">取消操作令牌</param>
        /// <returns>返回操作结果，包含受影响的总行数和状态信息</returns>
        public async Task<ApiResult<int>> Handle(AddReturnApplicationCommands request, CancellationToken cancellationToken)
        {
            try
            {
                ApiResult<int> result = new ApiResult<int>();
                int totalAffectedRows = 0;

                // 生成回收编码和时间戳
                string returnNumber = "HS" + DateTime.Now.ToString("yyyyMMddHHmmss");
                string itemBarcode = "WPTM" + DateTime.Now.ToString("yyyyMMddHHmmss");
                DateTime now = DateTime.Now;

                // 开始数据库事务
                db.Ado.BeginTran();
                try
                {
                    // 1. 映射并添加回收申请主表
                    var returnApp = mapper.Map<ReturnApplication>(request);
                    returnApp.Itembarcode = itemBarcode;
                    returnApp.ReturnNumber = returnNumber;
                    returnApp.IsDelete = false;
                    returnApp.Applicationtime = now;
                    returnApp.ReturnDate = now;

                    // 插入回收申请并获取ID
                    var appId = await db.Insertable(returnApp).ExecuteReturnIdentityAsync();
                    if (appId <= 0)
                    {
                        db.Ado.RollbackTran();
                        return new ApiResult<int>
                        {
                            Code = ApiEnums.添加失败,
                            Msg = "回收申请保存失败",
                            Data = 0
                        };
                    }
                    totalAffectedRows++;

                    // 2. 处理关联物品
                    if (request.Createid != null && request.Createid.Any())
                    {
                        // 获取物品信息
                        var items = await db.Queryable<ItemTable>()
                            .Where(i => request.Createid.Contains(i.ItemId) && !i.IsDelete)
                            .ToListAsync();

                        if (items.Any())
                        {
                            // 构建回收物品关联列表
                            var recycleItems = items.Select(item => new Recycleitems
                            {
                                ReturnApplicationId = appId,
                                ItemId = item.ItemId,
                                // 可以在这里设置其他需要的字段
                            }).ToList();

                            // 批量插入回收物品关联
                            var itemAffectedRows = await db.Insertable(recycleItems).ExecuteCommandAsync();
                            totalAffectedRows += itemAffectedRows;

                            if (itemAffectedRows <= 0)
                            {
                                db.Ado.RollbackTran();
                                return new ApiResult<int>
                                {
                                    Code = ApiEnums.添加失败,
                                    Msg = "回收物品关联保存失败",
                                    Data = 0
                                };
                            }
                        }
                    }

                    // 提交事务
                    db.Ado.CommitTran();

                    result.Code = ApiEnums.添加成功;
                    result.Msg = $"成功保存回收信息及{totalAffectedRows - 1}条物品关联";
                    result.Data = totalAffectedRows;
                }
                catch (Exception ex)
                {
                    // 发生异常时回滚事务
                    db.Ado.RollbackTran();
                    return new ApiResult<int>
                    {
                        Code = ApiEnums.添加失败,
                        Msg = $"保存回收信息时出错: {ex.Message}",
                        Data = 0
                    };
                }

                return result;
            }
            catch (Exception ex)
            {
                return new ApiResult<int>
                {
                    Code = ApiEnums.添加失败,
                    Msg = ex.Message,
                    Data = 0
                };
            }
        }
    }
}